<#--VXE-GRID-TS-->
//表格变量
const gridOptions = reactive(buildVxeGridOptions());//vxe-grid 的参数，包括表格数据
const aggregationData = reactive({aggregations:[]});//表格数据的统计值

//定义查询项
<#list pTableConfig.queryColumns as queryColumn>
const ${queryColumn.varName}ColumnFilter = reactive(new FilterColumn('${queryColumn.caption!''}', new FilterValue('${queryColumn.varName}', '${queryColumn.filterDataType}', '${queryColumn.querySqlOperator}', ${(queryColumn.searchFieldDroplist!false)?c}, ${(queryColumn.searchFieldCheckboxes)?c} ), "${queryColumn.unit!''}")); // ${queryColumn.columnCaption!''} 
</#list>
//查询项集合
const filterColumns = new FilterColumns([
<#list pTableConfig.queryColumns as queryColumn>
    ${queryColumn.varName}ColumnFilter<#sep>,</#sep>
</#list>
]);

<#if pTableConfig.useRecurseQuery==true>const onlyDirectly${pTable.className} = ref(false);//只看直属${pTable.tableCaption!}</#if>

/** 整理统计数据 */
const statData = computed(() => {
  let statData_ = {
      total: new ${pTable.className}StatData<#list pTableConfig.groupByColumns as groupByColumn>
      , ${groupByColumn.varName}_1:new ${pTable.className}StatData, ${groupByColumn.varName}_2:new ${pTable.className}StatData, ${groupByColumn.varName}_3:new ${pTable.className}StatData</#list>};
  if(aggregationData.aggregations && aggregationData.aggregations.length > 0){
    for(let i=0; i<aggregationData.aggregations.length; i++){
      let row : ${pTable.className}Stats = aggregationData.aggregations[i] as ${pTable.className}Stats;
      if(row.aggregateGroupName == 'total'){
        <#list pTableConfig.allAggregateColumns as aggColumn >
        statData_.total.${aggColumn.varName} = row.${aggColumn.varName};
        </#list>
      }
      <#list pTableConfig.groupByColumns as groupByColumn>
      if(row.aggregateGroupName == '${groupByColumn.varName}'){
        if(row.${groupByColumn.varName} == '1'){  //此处由模板自动生成，需要根据实际字典项的代码值进行修改。
          <#list pTableConfig.allAggregateColumns as aggColumn >
          statData_.${groupByColumn.varName}_1.${aggColumn.varName} = row.${aggColumn.varName};
          </#list>
        }else if(row.${groupByColumn.varName} == '2'){
          <#list pTableConfig.allAggregateColumns as aggColumn >
          statData_.${groupByColumn.varName}_2.${aggColumn.varName} = row.${aggColumn.varName};
          </#list>
        }else if(row.${groupByColumn.varName} == '3'){
           <#list pTableConfig.allAggregateColumns as aggColumn >
           statData_.${groupByColumn.varName}_3.${aggColumn.varName} = row.${aggColumn.varName};
           </#list>
        }
      }
      </#list>
    }
  }
  return statData_;
});


/** 构造 vxe-grid 的参数 */
function buildVxeGridOptions(){
  let gridOptions = buildDefaultVxeGridOptions();//构造vxe-grid的默认属性
  let gridProps : VxeGridProps = { //本页面定制的属性
<#if dataGrid.chkboxColumn!false == true>
  highlightCurrentRow:false,
  <#if dataGrid.chkboxMultiChked!false == true>
      checkboxConfig:{highlight: true},
  <#else>
      radioConfig:{highlight: true},
  </#if>
</#if>
<#if dataGrid.gridColumnLine!false == false>
      border:"inner",
</#if>
    columns: [
<#if dataGrid.lineNumberColumn!false == true>
      { type: 'seq', title:'序号', width: 50, align:'center', fixed:'left'},
</#if>
<#if dataGrid.chkboxColumn!false == true>
  <#if dataGrid.chkboxMultiChked!false == true>
      { type: 'checkbox', width: 50, align:'center', fixed:'left'},
  <#else>
      { type: 'radio', width: 50, align:'center', fixed:'left'},
  </#if>
</#if>
<#list pTableConfig.gridColumns as col>
      { field: '${col.gridFieldName}', title: '${col.columnCaption!''}<#if (col.unit!'')?length gt 0>(${col.unit})</#if>',<#rt>
      sortable:${(col.sortable!false)?c}, width: ${col.gridColumnWidth!120}, align:'${col.align!'left'}'<#t>
      <#if (col.fixed!false)==true>, fixed:'left'</#if><#t>
      <#if (col.unit!'')?contains('元')>, formatter:({ cellValue })=> cellValue?'￥'+cellValue:'-'</#if><#t>
      <#if col.isDateTime>, formatter:({ cellValue })=> myutil.fmtDateMinute(cellValue)</#if><#t>
      <#if (col.codeType!'')?length gt 0>, slots:{default:'${col.varName}Column'}</#if><#t>
      ,showOverflow: true}<#sep>,</#sep><#nt>
</#list>
<#if dataGrid.hasOptColumn==true>
      ,{ title:'操作', width: ${opColWidth}, align:'center', slots:{default:'operationColumn'}, fixed:'right'}
</#if>
    ]
  };
  gridOptions.pager.pageSize = ${dataGrid.pageSize!10};
  Object.assign(gridOptions.gridProps, gridProps);

  //排序事件的回调函数
  gridOptions.onSortChanged = function(field:string, order:string){
    console.log(`sort field:${r'${field}'}, order:${r'${order}'}`);
    get${pTable.className}List();
  }
  return gridOptions;
}

<#if dataGrid.pagination!false == true>
/** 分页组件事件回调（PageIndex或者PageSize发生变化时） */
const onPagerChange = (page: number, pageSize: number) =>{
  get${pTable.className}List();
}
</#if>

/**从服务端获取数据（根据新的参数）*/
async function get${pTable.className}List(){
  <#if pTableConfig.linkToTree==true>if(!curr${catalogTable.className}.id)return; </#if>
  gridOptions.gridProps.loading = true;//正在加载
  try{
    let response : any = await ${pTable.beanName}Service.get${pTable.className}ExListAndStats(<#rt>
      <#lt><#if pTableConfig.linkToTree==true>curr${catalogTable.className}.id, </#if><#rt>
      <#lt><#if pTableConfig.useRecurseQuery==true>!onlyDirectly${pTable.className}.value, </#if><#rt>
      <#lt>filterColumns.getQueryFilters(),
        new QueryConfig(<#if dataGrid.pagination!false == true>gridOptions.pager.pageIndex, gridOptions.pager.pageSize,<#else>0, -1,</#if> gridOptions.sorter.field, gridOptions.sorter.order));
    let listBO = response.data as ListBO;
    actionState.value.setActionState(listBO.authTag, listBO.lockState, listBO.lockState);
    gridOptions.gridProps.data = listBO.items;//表格数据
    aggregationData.aggregations = listBO.aggregations;
    let currPager:any = listBO.pager;
    gridOptions.gridProps.seqConfig = {startIndex: currPager.startRows};//重新设置行号的起始值
    gridOptions.pager.totalRows = currPager.totalRows as number;//重新设置总记录数
<#list pTableConfig.queryColumns as queryColumn>
<#if (queryColumn.codeType!'')?length gt 0>
    if(!${queryColumn.varName}ColumnFilter.codeItems){//第一次查询时，设置查询条件的下拉列表
      ${queryColumn.varName}ColumnFilter.codeItems = listBO.codeTypes["${queryColumn.varName}"];
    }
</#if>
</#list>
<#list pTableConfig.columns as column>
<#if (column.codeType!'')?length gt 0 && column.editMenu!false==true>
    ${column.varName}Items.value = listBO.codeTypes["${column.varName}"];
</#if>
</#list>
  }finally{
    gridOptions.gridProps.loading = false;
  }
}

/** 重置查询条件 */
function resetQueryFilters(){
  filterColumns.reset();
  get${pTable.className}List();
}

<#if dataGrid.optrCellEditBtn!false == true>
/**cell编辑按钮点击事件*/
async function edit${pTable.className}BtnClick(id : number) {
  ${pTable.beanName}FormModal.showModal(id);//显示表单对话框
}
</#if>

<#if dataGrid.toolbarEditBtn!false == true>
/**toolbar上的编辑按钮点击事件*/
async function edit${pTable.className}ToolBtnClick() {
<#if dataGrid.chkboxColumn!false == true>
  <#if dataGrid.chkboxMultiChked!false == true>
  let rows = (${pTable.beanName}Grid.value as any).getCheckboxRecords();
  if(rows.length != 1){
    message.warn('请先在表格内选中一行（不能选中多行）数据后再编辑');
    return;
  }
  let row = rows[0];
  <#else>
  let row = (${pTable.beanName}Grid.value as any).getRadioRecord();
  </#if>
<#else>
  let row = (${pTable.beanName}Grid.value as any).getCurrentRecord();
</#if>
  if(row){
    ${pTable.beanName}FormModal.showModal(row.${pTable.idVarName});//显示表单对话框
  }else{
    message.warn('请先在表格内选中数据后再编辑');
  }
}
</#if>

<#if dataGrid.toolbarDelBtn!false == true>
/**toolbar上的删除按钮点击事件*/
async function del${pTable.className}ToolBtnClick() {
<#if dataGrid.chkboxColumn!false == true>
  <#if dataGrid.chkboxMultiChked!false == true>
  let rows = (${pTable.beanName}Grid.value as any).getCheckboxRecords();
  if(rows.length != 1){
    message.warn('请先在表格内选中一行（不能选中多行）数据后再编辑');
    return;
  }
  let row = rows[0];
  <#else>
  let row = (${pTable.beanName}Grid.value as any).getRadioRecord();
  </#if>
<#else>
  let row = (${pTable.beanName}Grid.value as any).getCurrentRecord();
</#if>

  if(row){
    delete${pTable.className}BtnClick(row.${pTable.idVarName}, row.${pTable.nameVarName})
  }else{
    message.warn('请先在表格内选中数据后再编辑');
  }
}
</#if>
<#if pTableConfig.showFormDialog>
/**表单【确定】按钮点击事件*/
async function ${pTable.beanName}FormModalHandleOk() {
  let response = await ${pTable.beanName}FormModal.submit(${pTable.beanName}Form.value as IForm);
  console.log("after ok button clicked:");
  console.log(response);
  get${pTable.className}List();
}
</#if>

<#if dataGrid.optrCellDelBtn!false == true || dataGrid.toolbarDelBtn!false == true>
/**cell上的删除按钮事件*/
async function delete${pTable.className}BtnClick(id : number, name : string){
  myutil.confirmForDelete(`确认删除 ${r'${name}'} 吗?`).then(async () => {
      await ${pTable.beanName}Service.delete${pTable.className}(id);
      get${pTable.className}List();
  });  
}
</#if>

<#if dataGrid.toolbarExpBtn!false == true>
/**toolbar上的导出按钮*/
async function export${pTable.className}BtnClick(){
  await ${pTable.beanName}Service.export${pTable.className}ExListAndStats(filterColumns.getQueryFilters(),  new QueryConfig(0, -1, gridOptions.sorter.field, gridOptions.sorter.order));
}
</#if>

<#list pTableConfig.gridColumns as col>
<#if (col.codeType!'')?length gt 0 && col.editMenu!false==true>
const ${col.varName}Items = ref(new Array<{code:string, name:string}>());//字典值
async function change${col.propName}(row:any, ${col.varName} :any){//当通过下拉菜单更改${col.caption!}时
  await ${pTable.beanName}Service.updateProp(row.${pTable.idVarName}, "${col.varName}", ${col.varName});
<#assign commentGet='' commentList='//'>
<#if (col.aggregateGroup!false) == true || (col.aggregateFunc!'')?length gt 0><#assign commentGet='//' commentList=''></#if> <#-- 判断这个属性的修改是否会影响统计值 -->
  ${commentGet}let response : any = await ${pTable.beanName}Service.get${pTable.className}(row.${pTable.idVarName});//如果此属性的改变，涉及到统计数据的改变，则需要注释掉此段代码，使用下面的get${pTable.className}List()调用。
  ${commentGet}let ${pTable.beanName} = response.data;
  ${commentGet}row.${col.varName} = ${pTable.beanName}.${col.varName};
  ${commentGet}row.${col.varName}Caption = ${pTable.beanName}.${col.varName}Caption;
  ${commentList}get${pTable.className}List();//如果此属性的改变，涉及到统计数据的改变，则需要调用此函数，把上面的get${pTable.className}函数注释掉。
}
</#if>
</#list>

<#if pTable.isLockByMaster>
async function masterLockStateChange(masterId:number, lockState:number){
  try{

    let response = await ${pTable.beanName}Service.changeMasterLockState(<#if pTable.foreignColumn??>masterId, </#if>lockState);
    return Promise.resolve(lockState);
  }catch(ex:any){
    return Promise.reject(ex);
  }
}
</#if>
<#if pTable.isLockByRow>
async function ${pTable.beanName}RowLockStateChange(id:number, lockState:number){
  try{
    let response = await ${pTable.beanName}Service.changeLockState(id, lockState);
    return Promise.resolve(lockState);
  }catch(ex:any){
    return Promise.reject(ex);
  }
}
</#if>